import VGE from '../../VGE';
import { login } from './login';
import { getBIMBaseToken } from './utils.js';

const getAccessToken = (stationName) => (callBack) => {
	// callBack(
	// 	'eyJhbGciOiJSUzI1NiJ9.eyJzY29wZSI6WyJvYnY6cmVhZCJdLCJleHAiOjE3MTM1MzI4MzMsImNsaWVudF9pZCI6ImFlY3dvcmtzLW9idi1jb21tdW5pdHkiLCJqdGkiOiI4NDVkOGM4OC0yMWVkLTQ4MGUtYTE1Ni05ZjlmY2MxYmQxY2MifQ.TRPRZDPl7b5i-8xooxD5gna0O-MmFOVltggbqfs6hsWenyAN3Srjpx2SF0KJACgyTej89GWZCkgT5QudV6Rr6OFjlBWfIU5g2h2lhgXvLOa0GJwNG013Ds06rg2hSAs0QvXmdRd5choImiWg9xde9tAOZcGwDw_V-tmJZWrx4XfZLSO-U9vXm_9pZfNK8XJCQWJyh4QllHg_tPUiYGOf-0eFj1s-IbLnlDRBTGrpSgNVLDPpvCjH_dNl4KKBGBiIiMrxAkvrFJAqd0Ilxtf0zxqksLTG0WV7i2UGTV3YONkL56AvmU7Pw6SfoCdVMt6PFAyZ3Y54wej7shi2tXbjLQ',
	// 	36000
	// );
	callBack(getBIMBaseToken(stationName), 36000);
};

/**
 * 模型浏览入口
 */
export default class BIMBaseApp {
	static async open(sceneData = {}, callback) {
		try {
			const { sceneUrl, container, cameraParams, homeView, serviceInfo } = sceneData;

			const [urn, jobType] = sceneUrl.split('|');

			const iOBV = (this.iOBV = await this.loadScript());

			const akskPair = {
				origin: window.origin,
				stationName: serviceInfo.stationName,
				ak: serviceInfo.stationUsername,
				sk: serviceInfo.stationPassword
			};
			await login(akskPair);

			// 创建实例需要传入的参数，部署环境serviceConfig 和 用户有效期getAccessToken
			const applicationOptions = {
				// 配置 OBV 服务端（BIMServer）API 服务的 origin，这个适合于私有部署的用户使用
				getAccessToken: getAccessToken(akskPair.stationName),
				refreshAccessToken: getAccessToken(akskPair.stationName),
				serviceConfig: {
					origin: window.origin,
					apiContextPath: '/graphics-engine/bimserver/viewing/v3'
				},
				lang: 'zh'
			};

			const viewer3dConfig = {
				addinConfigs: [
					{
						id: 'OBVAddins.Markup',
						noButton: false
					},
					{
						id: 'OBVAddins.Marker',
						noButton: false
					}
					// {
					// 	id: 'OBVAddins.Linkage',
					// 	noButton: false,
					// 	viewer2dContainer,
					// 	application
					// }
				]
			};

			// const viewer2dContainer = document.getElementById('viewer2d');

			const dom = await VGE.util.findOrCreateDom(container, true, true);
			// 实例化 Builder，用于模型加载
			const builder = new iOBV.Api.ObvBuilder();
			// 创建 Application 对象
			const application = await builder.buildApplication(applicationOptions);
			// 创建 document 管理视图，加载完成后可以调用接口
			const obvDocument = await builder.loadDocument(application, urn, jobType); // 第三个参数代表模型格式以及转换参数（全量、流式）
			// 创建 viewer 容器, 创建API
			const obvApi = await builder.buildViewer3d(application, dom, viewer3dConfig);
			// 获取三维视图
			const viewer3dItems = obvDocument.get3dGeometryItems();
			builder.load3dModels(obvApi, {
				obvDocument: obvDocument,
				viewer3dItem: viewer3dItems[0]
			});
			const viewer = (this.viewer = obvApi);
			callback && callback(obvApi);

			return viewer;
		} catch (e) {
			console.error(e?.message ? e.message : e);
		}
	}

	static async loadScript() {
		if (window.OBV) return window.OBV;
		return new Promise((resolve) => {
			const $link = document.createElement('link');
			$link.rel = 'stylesheet';
			$link.type = 'text/css';
			$link.href = 'https://api.cloud.pkpm.cn/bimviewer/viewer/v5/obv.css';
			window.document.head.appendChild($link);

			const $link2 = document.createElement('link');
			$link2.rel = 'resource';
			$link2.type = 'application/l10n';
			$link2.href = 'https://api.cloud.pkpm.cn/bimviewer/viewer/v4/locale/locale.properties';
			window.document.head.appendChild($link2);

			const $script = document.createElement('script');
			$script.src = 'https://api.cloud.pkpm.cn/bimviewer/viewer/v5/obv.js';
			window.document.body.appendChild($script);
			$script.onload = () => {
				resolve(window.OBV);
			};
		});
	}

	static async close() {
		try {
			if (this.viewer) {
				// 构力没有提供析构函数(destructor)
				this.viewer = null;
			}
		} catch (e) {
			console.error(e?.message ? e.message : e);
		}
	}
	static async login(akskPair) {
		login(akskPair);
	}
}

BIMBaseApp.camera = null;
BIMBaseApp.tools = null;
BIMBaseApp.marker = null;
BIMBaseApp.layer = null;
BIMBaseApp.misc = null;
